package com.ruoyi.kindergarten.websocket;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/ws")
@Component
public class WebSocketService {
    private static final ConcurrentHashMap<String, Session> SESSIONS  = new ConcurrentHashMap<String, Session>();

    @OnOpen
    public void onOpen(Session session) {
        SESSIONS.put(session.getId(), session);
        System.out.println("session opened: " + session.getId());
    }
    @OnMessage
    public void onMessage(String message){
        broadcast(message);
        System.out.println("message received: " + message);
    }
    @OnClose
    public void onClose(Session session) {
        SESSIONS.remove(session.getId());
        System.out.println("session closed: " + session.getId());
    }
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void broadcast(String message) {
        for (Session value : SESSIONS.values()) {
            try{
                value.getBasicRemote().sendText(message);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
